<template>
  <el-card>
    <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
      <el-input
          ref="searchInput"
          v-model="searchKeyword"
          clearable
          placeholder="输入成果名称搜索"
          size="small"
          style="width: 260px"
          @clear="clearSearch"
      >
        <template #append>
          <el-button size="small" @click="debounceSearch(searchKeyword)">搜索</el-button>
        </template>
      </el-input>
      <div>
        <el-button size="small" type="success" @click="handleExportResearchInfo">导出科研信息</el-button>
      </div>
    </div>
    <div class="scroll-container">
      <el-table v-loading="loading" :data="researchList" style="width: 100%">
        <el-table-column label="成果类型" prop="type" width="120"/>
        <el-table-column label="成果名称" prop="name" width="180"/>
        <el-table-column label="发表期刊" prop="journal"/>
        <el-table-column label="收录情况" prop="inclusion" width="120"/>
        <el-table-column label="获奖情况" prop="awards" width="120"/>
        <el-table-column label="发表时间" prop="date" width="120"/>
        <el-table-column label="成果描述" prop="description"/>
      </el-table>
    </div>
    <el-pagination
        v-if="total > 0"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        background
        layout="prev, pager, next"
        style="margin-top: 20px;"
        @current-change="handlePageChange"
    />
  </el-card>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import api, {iget} from '@/api'

const loading = ref(false)
const researchList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const searchInput = ref(null)

const fetchResearchList = async () => {
  loading.value = true
  try {
    const res = await iget('/research/list', null, {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    researchList.value = res.data.result.records
    total.value = res.data.result.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  pageNum.value = page
  fetchResearchList()
}


const handleExportResearchInfo = () => {
  const exportWithRetry = async (retryCount = 2) => {
    try {
      ElMessage.success('正在导出科研成果信息...')
      const response = await api.get('/export/researchInfo', {
        responseType: 'blob'
      })
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '科研成果信息.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      if (retryCount > 0) {
        await exportWithRetry(retryCount - 1);
      } else {
        console.error('导出科研成果信息失败,' + error);
        ElMessage.error('网络不稳定，下载中断');
      }
    }
  }
  exportWithRetry();
};


const debounceSearch = debounce(async (keyword) => {
  if (keyword.trim() === '') {
    await fetchResearchList()
    return
  }
  try {
    loading.value = true
    const res = await iget('/research/search', {
      params: {
        keyword: keyword,
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    researchList.value = res.data.result.records
    total.value = res.data.result.total
  } catch (error) {
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}, 300)

const clearSearch = () => {
  searchKeyword.value = ''
  ElMessage.success('已清空输入')
  debounceSearch('')
}

function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

watch(searchKeyword, (newVal) => {
  debounceSearch(newVal)
})

onMounted(() => {
  fetchResearchList()
})
</script>

<style scoped>
.el-card {
  margin: 15px;
}

.scroll-container {
  overflow-x: auto;
  width: 100%;
}

.el-table {
  min-width: 100%;
}
</style>